package com.surelution.lansao

import com.surelution.lansao.crawler.ProcessHelper;

class MobileGateController {

	private Partner partner
	private Member member
	
	def beforeInterceptor = {
		def serverName = request.getServerName()
		if(serverName) {
			partner = Partner.findByDomainName(serverName)
		}
		if(params.flashId) {
			def link = Link.findByUuid(params.flashId)
			if(link) {
				member = link.member
			}
		}
	}

    def index = {
		
	}
	
	def menu = {
		def mas
		if(member) {
			mas = MemberAddress.findAllByMember(member)
		}
		def chosenId = params.id
		def items
		if(partner) {
			items = Item.findAllByPartnerAndAvailable(partner, true)
		}
		[items:items, chosenId:chosenId, addresses:mas]
	}
	
	def placeOrder = {
		def order
		if(partner) {
			def address = MemberAddress.get(params.int('address.id'))
			if(!address) {
				flash.message = "请选择一个送餐地址！如果您还没有添加任何送餐地址，请先添加送餐地址"
				redirect(action:"menu", params:[flashId: params.flashId])
			}
			order = new Order(partner:partner, member:member, orderTime:new Date(), 
				status: OrderStatus.status(OrderStatus.NEW), deliveryAddress:address.toString())
			def items = Item.findAllByPartnerAndAvailable(partner, true)
			def all = []
			items.each {
				def count = params.int("item_${it.id}")
				if(count > 0) {
					def orderItem = new OrderItem(item:it, amount:count, order:order)
					all.add(orderItem)
				}
			}
			if(all.size() > 0) {
				order.save(flush:true)
				all.each {
					it.save(flush:true)
				}
				StringBuilder sb = new StringBuilder()
				sb.append("您已成功订餐，餐品如下：\n")
				all.each {
					sb.append(it.item.name)
					sb.append(it.amount)
					sb.append("份\n")
				}
				sb.append("送餐地址如下：")
				sb.append(order.deliveryAddress)
				ProcessHelper.sendMessage(partner, member, sb.toString())
			} else {
				flash.message = "请至少选择一项餐品"
				redirect(action:"menu", params:[flashId: params.flashId])
			}
		}
		
		[order:order]
	}
	
	def editAddress = {
		def mas
		
		if(member) {
			mas = MemberAddress.findAllByMember(member)
		}
	
		[flashId:params.flashId, memberAddresses:mas]
	}
	
	def saveAddress = {
		def address = params.address
		def unit = params.unit
		println member
		println partner
		MemberAddress ma = new MemberAddress(member:member, unit:unit, address:address, lastDelivery:false, verified:false)
		ma.save(flush:true)
		flash.message = "您已成功保存送餐地址。"
	}
}
